/**
 * 队列对象
 */
export class Queue {
    private static instance: Queue = new Queue();
    private queue: Function[] = [];
    private running: boolean = false;
    private stop: boolean = false;

    private constructor() {}
    //获得实例对象
    public static getInstance(): Queue {
        return this.instance;
    }

    // 添加方法入队列
    add(...fn) {
        for (var i in arguments) {
            this.queue.push(arguments[i]);
        }
        this.next()
    }

    // 执行下一个
    private next() {
        /* 
            如果没有运行中的方法
            没有停止运行
        */
        if (!this.running && !this.stop) {
            this.run();
        }
    }

    // 运行下一个
    private run() {
        this.running = true;
        if (this.queue.length < 1 || this.stop) {
            this.running = false;
            return;
        }

        var whileRun = this.queue.shift();
        if(whileRun && typeof whileRun === 'function') {
            whileRun().then(() => {
                this.running = false;
                this.next();
            }).catch(e => {
                this.running = false;
                this.next();
            })
        }
    }

    // 暂停队列
    pause() {
        this.stop = true;
    }

    // 重启队列
    resume() {
        this.running = false;
        this.stop = false;
        this.next()
    }

    // 清除队列数组
    clear() {
        this.queue = [];
        return this.queue;
    }

    // 获取队列数组
    get() {
        return this.queue;
    }
}

export default Queue.getInstance();